package com.lin.controller;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Controller
@RequestMapping("/shiro")

public class ShiroController {

    @RequestMapping("/unauthorized")
    public String unauthorized(HttpServletRequest request) {
        if (isAjaxRequest(request)) {
            return "redirect:/shiro/unauthorizedReturnJson";
        } else {
            return "redirect:/shiro/unauthorizedReturnUnauthorized";
        }
    }

    /**
     * 权限不足返回json
     */
    @RequestMapping("/unauthorizedReturnJson")
    @ResponseBody
    public Map<String, Object> unauthorizedReturnJson() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", false);
        map.put("msg", "您的权限不足");
        return map;
    }

    /**
     * 权限不足跳转403页面
     */
    @RequestMapping("/unauthorizedReturnUnauthorized")
    public String unauthorizedReturnUnauthorized(HttpServletRequest request, HttpSession session) {
        String menuId = (String) session.getAttribute("menuId");
        request.setAttribute("ddId", menuId);
        return "error/unauthorized";
    }

    /**
     * 是否是Ajax请求
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        return requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest");
    }
}
